package Server

import (
	"fmt"
	"net"
	"net/http"
	"net/rpc"
	"sync/atomic"
)

var SELFInt int32 = 1

type test struct {
	fileName string
	line     int
	fullPath string
	funcName string
}

func rpcHttpTest() {
	obj := new(SelfType)
	rpc.Register(obj)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", ":1998")
	if e != nil {
		fmt.Println("occ err :", e)
	}
	http.Serve(l, nil)
}

func rpcTcpTest() {
	obj := new(SelfType)
	rpc.Register(obj)
	tcpAddr, _ := net.ResolveTCPAddr("tcp", ":10020")
	listener, _ := net.ListenTCP("tcp", tcpAddr)
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		go rpc.ServeConn(conn)
	}
}

type RpcTestStruct struct {
	A    int
	Name string
	Ctx  string
}

type SelfType struct {
	Name string
}

type MethodsType struct {
	A        int
	TestFunc func(string)
	B        string
	SType    *SelfType
	TestMap  map[int]interface{}
}

func (t *SelfType) SayHello(x *RpcTestStruct, m *int32) error {
	fmt.Println("I'm ", x.Name, " and Age is ", x.A, " this talk is ", x.Ctx)
	*m = atomic.AddInt32(&SELFInt, 1)
	return nil
}

func (t *SelfType) TellMethod(x *RpcTestStruct, m *MethodsType) error {
	m.A = x.A + 10
	m.TestFunc = TestRPCMethods()
	m.SType = new(SelfType)
	m.SType.Name = "ni hao"
	m.TestMap = make(map[int]interface{}, 3)
	m.TestMap[0] = "x"
	m.TestMap[1] = 1
	return nil
}

func TestRPCMethods() func(string) {
	return func(x string) {
		fmt.Println(x, "  is a Test")
	}
}
